<script>
import * as api from "@/api/app_SubCom/index"

export default {
  name: "orgSelect",
  props: {
    selectType: {
      type: Array,
      default: () => ["user", "role", "teamRole", "dept", "userGroup", "custom"]
    },
    autoSelection: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: true,
      search: "",
      tableData: [],
      tabs: "getUserList",
      page: {
        current: 1,
        size: 20,
        totalRows: 0
      },

      selectionData: [],

      tableDataSelect: [],
      tableDataSelection: [],


      autoSelection_: this.autoSelection,
      onlySelection: [],

      typeList: {
        "user": "用户",
        "role": "角色",
        "teamRole": "团队角色",
        "dept": "组织",
        "userGroup": "用户组",
        "custom": "自定义",
      }
    }
  },
  computed: {
    typeName() {
      return this.tabs.replace("get", "").replace("List", "").replace(/^[A-Z]/, (match) => match.toLowerCase());
    }
  },
  methods: {
    getSelectData() {
      return this.tableDataSelect;
    },

    del() {
      if (this.tableDataSelection.length === 0) {
        this.$message.warning("请选择需要删除的数据")
        return;
      }
      let data = JSON.parse(JSON.stringify(this.tableDataSelect));
      this.tableDataSelect = [];
      let ids = this.tableDataSelection.map(i => i.id);
      data.forEach(i => {
        if (!ids.includes(i.id)) {
          this.tableDataSelect.push(i)
        }
      })
      this.autoSelection_ = this.tableDataSelect;
      this.setAutoSelection();
    },

    addTo() {
      if (this.selectionData.length === 0) {
        this.$message.warning("请选择数据");
        return
      }
      if (this.tableDataSelect.length === 0) {
        this.tableDataSelect = this.selectionData.map(i => {
          return {name: i.name, id: i.id, type: i.type};
        })
      } else {
        if (this.tabs === "getCustomList") {
          this.tableDataSelect = this.tableDataSelect.filter(i => i.type !== "custom");
          this.tableDataSelect.push(this.selectionData[0])
        } else {
          let ids = this.tableDataSelect.map(i => i.id);
          this.selectionData.forEach(item => {
            if (!ids.includes(item.id)) {
              this.tableDataSelect.push({
                name: item.name,
                id: item.id,
                type: item.type
              })
            }
          })
        }
      }
      this.autoSelection_ = this.tableDataSelect;
      this.setAutoSelection();
    },
    getTableData() {
      this.loading = true;
      let val = this.tabs;
      let params = {};
      if (["getUserList", "getRoleList", "getTeamRoleList", "getUserGroupList"].includes(val)) {
        params = {
          current: this.page.current,
          size: this.page.size
        }
        if (this.search) {
          let obj = {nameCn: this.search};
          if (val === "getUserList") obj = {username: this.search}
          Object.assign(params, obj)
        }
      }

      if (["getCustomList"].includes(val)) {
        params = {
          size: -1, type: 'user', status: 1
        }
      }
      let deepCopy = (obj) => {
        // 如果传入的不是对象类型，则直接返回
        if (typeof obj !== 'object' || obj === null) {
          return obj;
        }
        // 定义一个返回的变量
        let copy = {};
        // 判断传入的对象是数组还是对象
        if (obj.constructor === Array) {
          copy = [];
        }
        // 遍历对象的属性
        for (let key in obj) {
          // 判断对象是否有该属性
          if (obj.hasOwnProperty(key)) {
            // 如果该属性是对象类型，则递归调用该函数
            if (typeof obj[key] === 'object' && obj[key] !== null) {
              copy[key] = deepCopy(obj[key]);
            } else {
              // 否则，直接复制属性值
              if (key !== "hasChildren") {
                copy[key] = obj[key];
                copy["type"] = "dept"
              }
            }
          }
        }
        return copy;
      }
      api[val](params).then(res => {
        let data = res.data.data;
        if (["getRoleList", "getUserList", "getTeamRoleList", "getUserGroupList"].includes(val)) {
          this.page.totalRows = data.totalRows;
          this.tableData = data.list
          if (val === "getUserList") {
            this.tableData = data.list.map(i => {
              i.id = i.pid;
              i.type = "user";
              return i;
            });
          }
          if (val === "getRoleList") {
            this.tableData = data.list.map(i => {
              i.id = i.pid;
              i.name = i.nameCn;
              i.type = "role";
              return i;
            });
          }
          if (val === "getTeamRoleList") {
            this.tableData = data.list.map(i => {
              i.id = i.pid;
              i.name = i.nameCn;
              i.type = "teamRole";
              return i;
            });
          }
          if (val === "getUserGroupList") {
            this.tableData = data.list.map(i => {
              i.name = i.nameCn;
              i.id = i.pid;
              i.type = "userGroup";
              return i;
            });
          }
        } else if (val === "getDeptList") {
          this.tableData = deepCopy(data);
        } else {
          data.records.forEach(item => {
            item.id = item.expression
            item.type = "custom"
          })
          this.tableData = data.records;
        }
        this.$nextTick(() => {
          this.setAutoSelection();
        })
        this.loading = false;
      })
    },

    handleSizeChange(val) {
      this.page.size = val;
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.current = val;
      this.getTableData()
    },
    selectionChange(val) {
      if (this.tabs === "getCustomList") {
        val.forEach((item, index) => {
          if (index !== val.length - 1) {
            this.$refs["elTable"].toggleRowSelection(item, false)
          } else {
            this.selectionData = [item]
          }
        })
      } else {
        this.selectionData = val
      }
    },
    setAutoSelection() {
      let data = this.onlySelection = this.autoSelection_.filter(i => i.type === this.typeName);
      let ids = data.map(i => i.id);
      this.tableData.forEach(item => {
        if (ids.includes(item.id)) {
          this.$refs["elTable"].toggleRowSelection(item, true)
        } else {
          this.$refs["elTable"].toggleRowSelection(item, false)
        }
      })
    }
  },
  mounted() {
    if (this.selectType.length === 0) {
      throw new Error("selectType is required");
    }
    let type = this.selectType[0]
    if (type === "user") this.tabs = "getUserList";
    if (type === "role") this.tabs = "getRoleList";
    if (type === "teamRole") this.tabs = "getTeamRoleList";
    if (type === "dept") this.tabs = "getDeptList";
    if (type === "userGroup") this.tabs = "getUserGroupList";
    if (type === "custom") this.tabs = "getCustomList";

    this.selectionData = [];
    this.tableDataSelect = this.autoSelection_;
    this.tableDataSelection = [];
    this.getTableData();
  }
}
</script>

<template>
  <div class="orgSelect">
    <div class="os-l">
      <el-tabs size="mini" v-model="tabs" @tab-click="search='',getTableData()">
        <el-tab-pane label="用户" name="getUserList" v-if="selectType.includes('user')"></el-tab-pane>
        <el-tab-pane label="角色" name="getRoleList" v-if="selectType.includes('role')"></el-tab-pane>
        <el-tab-pane label="团队角色" name="getTeamRoleList" v-if="selectType.includes('teamRole')"></el-tab-pane>
        <el-tab-pane label="组织" name="getDeptList" v-if="selectType.includes('dept')"></el-tab-pane>
        <el-tab-pane label="用户组" name="getUserGroupList" v-if="selectType.includes('userGroup')"></el-tab-pane>
        <el-tab-pane label="自定义" name="getCustomList" v-if="selectType.includes('custom')"></el-tab-pane>
      </el-tabs>

      <div>
        <el-tag size="mini">{{ typeList[typeName] }}已选 <span
            style="font-weight: 600">{{ onlySelection.length }}</span> 条数据 (共选{{ tableDataSelect.length }}条数据)
        </el-tag>
        <p></p>
        <el-input size="mini" placeholder="请输入名称……" :disabled="['getDeptList','getCustomList'].includes(tabs)"
                  v-model="search">
          <el-button slot="append" icon="el-icon-search" :disabled="['getDeptList','getCustomList'].includes(tabs)"
                     @click="getTableData()"></el-button>
        </el-input>
        <p></p>
      </div>

      <el-table :data="tableData"
                ref="elTable"
                size="mini"
                height="calc(100% - 180px)"
                row-key="id"
                border
                v-loading="loading"
                @selection-change="selectionChange"
                :tree-props="{children: 'children'}">
        <el-table-column
            type="selection"
            align="center"
            width="40">
        </el-table-column>
        <el-table-column label="名称" prop="name"></el-table-column>
      </el-table>

      <div style="text-align: right;margin-top: 20px"
           v-if="['getUserList','getRoleList','getUserGroupList'].includes(tabs)">
        <el-pagination
            size="mini"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            layout="total, prev, pager, next"
            :current-page.sync="page.current"
            :page-size="page.size"
            :total="page.totalRows">
        </el-pagination>
      </div>
    </div>

    <div class="center-btn">
      <div>
        <el-button size="small" type="primary" icon="el-icon-arrow-right" @click="addTo"></el-button>
      </div>
    </div>

    <div class="os-r">
      <div style="margin-bottom: 10px">
        <el-button size="small" type="danger" @click="del">删除</el-button>
      </div>
      <el-table size="mini" :data="tableDataSelect" border height="calc(100% - 50px)"
                @selection-change="val=>tableDataSelection=val">
        <el-table-column
            type="selection"
            align="center"
            width="40">
        </el-table-column>
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="类型" prop="type">
          <template slot-scope="{row}">
            {{ typeList[row.type] }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<style scoped lang="scss">
.orgSelect {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  flex-wrap: nowrap;

  > div {
    border: 1px solid #f4f4f4;
    box-sizing: border-box;
    padding: 10px;
    width: 47%;
    height: 100%;
  }

  .os-l {
  }

  .center-btn {
    width: 6%;
    height: 100%;
    border: none;
    padding: 0;
    text-align: center;

    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .os-r {
  }
}
</style>
